import React, { Component } from 'react'
import style from './index.module.scss';
import {request} from "../../request/request";
import {connect} from "react-redux"

import { Image } from 'antd';
import MAlert from '../../base/MAlert';
import header from "../../base/Header/index";

import SkeletonDIY from "./Skeleton.jsx";
import CarouselDIY from "./Carousel.jsx";
const imgFallback = require("../../common/imageDefault/imgloaderr.png").default;

import {certificate_icon} from '../../common/icon/svg';

const addressIcon = require("../../common/icon_png/addressicon.png").default;

const favoIcon = require("../../common/icon_png/shoucang.png").default;
const favoIcon2 = require("../../common/icon_png/shoucang1.png").default;
const commIcon = require("../../common/icon_png/liuyan.png").default;
const chatIcon = require("../../common/icon_png/chat.png").default;
const buyIcon = require("../../common/icon_png/buy.png").default;

class BookInfoDetails extends Component {
    state={
        bookinfo:{bid:""},
        loading:true,
        visible:false,
        userinfo:{uid:""},
        item:{
            name:"画说写诗",
            description:"一本好书，值得细细品味",
            ISBN:"1235454345t",
            publisher:"新疆乌鲁木齐出版社",
            grade:5,
            author:"王小波",
            nickname:"王羲之书法独特",
            city:"邯郸",
            pro:"河北",
            price:"78.4",
            origin_price:"94",
            address:"永年区 东杨庄镇西杨庄村",
            getSelf:true,
            cover:require("../../common/image/home/swiper01.jpg"),
            head_url:require("../../common/image/home/swiper01.jpg"),
            stuAuth:null,
            bid:"",
            isFavo:"",
        },
        imgList:[
            require("../../common/image/home/swiper01.jpg").default,
            require("../../common/image/home/swiper02.jpg").default,
        ],
        flag:false,
        flag1:false,
        num:1,
        currComment:"",
        commentList:[],
    }

    setFavorite(){
        let {userinfo} = this.state;
        if(!userinfo.uid) return alert("请先登录!")

        let {item} = this.state;
        let {isFavo} = item;
        if(isFavo) isFavo = 0;
        else isFavo = 1;

        request({
            url:"/setFavorite",
            method:"POST",
            data:{ bid:item.bid,uid: userinfo.uid,isFavo}
        }).then(res=>{
            if(res.data.code==="01"){
                item.isFavo = isFavo;
                this.setState({item});
            }else{
                console.log(res);
                alert("收藏失败");
            }
        });
    }

    getBookInfo(){
        request({
            url:"/bookinfo",
            method:"GET",
            params:{
                uid:this.state.userinfo.uid,
                bid:this.props.match.params.bid,
            }
        }).then(res=>{
            console.log(res);
            
            if(res.data.code==="01"){
                if(typeof res.data.data !== "object"){
                   alert("请求数据失败")
                }else{
                   setTimeout(()=>{
                       this.setState({
                           loading:false,
                           item:{...res.data.data}
                       })
                   },500)
                }
            }
        })
    }

    showDrawer(flag){
        this.setState({
            visible: flag,
        });
    };

    getBookComments(){
        request({
            url:"/getBookComments?bid="+this.props.match.params.bid,
            method:"GET",
        }).then(res=>{
            let _res = res.data;
            if(_res.code == "01") {
                let commentList = _res.data;
                this.setState({commentList});
            }else{
                console.log("getBookComments 获取失败！");
            }
        });
    }

    sendComment(){
        let {currComment,userinfo,item} = this.state;
        if(!currComment) return;
        if(userinfo.bid){
            this.onClose();
            return alert("登录后才可评论！");
        };
        let commentObj = {
            cid: "",
            bid: item.bid, 
            comment: currComment,
            uid: userinfo.uid,
            head_url: userinfo.head_url,
            nickname: userinfo.nickname
        }
        request({
            url:"/sendComment",
            method:"POST",
            data:commentObj
        }).then(res=>{
            console.log(res.data)
            let _res = res.data;
            if(_res.code == "01") {
                let {currComment,commentList} = this.state;
                commentObj.cid = _res.data;
                commentObj.buildtime = new Date();
                currComment = "";
                commentList.unshift(commentObj);
                this.setState({currComment,commentList,visible:false});
                this.scrollEle.scrollTo({
                    top: 320,
                    behavior:"smooth",
                })
            }else{
                alert("发表失败！");
                this.onClose();
            }
        });
    }

    componentDidMount(){
        let temp = localStorage.getItem("userList");
        if(temp) this.setState({userinfo: JSON.parse(temp)});

        setTimeout(()=>{
            this.getBookInfo();
        },50);
        setTimeout(()=>{
            this.getBookComments();
        },100);

        setTimeout(()=>{
            console.log(this.state.item)
        },100)
    }

    //加入购物车 出现弹窗
    buy=()=>{
        this.setState({
            flag:true
        })
        setTimeout(()=>{
            this.setState({
                flag1:true
            })
        },)
    }
    //退出弹窗
    buyBack=()=>{
        this.setState({
            flag1:false
        })
        this.mark.style.transition="all 0.2s linear 0.2s"
        this.min.style.transition="all 0.2s linear"
        setTimeout(()=>{
            this.setState({
                flag:false
            })
        },400)
    }

    //购买数量加减
    dist=()=>{
        let {num} = this.state
        if(num>1){
            num--
        }
        this.setState({
            num
        })
    }
    add=()=>{
        let {num} = this.state
        num++
        this.setState({
            num
        })
    }
    //加入购物车
    jiaBuy(){
        let obj={...this.state.item,num:this.state.num,ischeck:true}
        this.props.getCar(JSON.parse(JSON.stringify(obj)));
        this.setState({num:1});
        this.buyBack()
    }

    // 跳转私聊
    goPrivateChat(){
        let {userinfo, item} = this.state;
        if(!userinfo.uid) return alert("请先登录!");

        this.props.history.push({
            pathname:"/privateChat", 
            state:{
                toUid:item.uid,
                tnickname: item.nickname,
                thead_url: item.head_url,
                tstuAuth: item.stuAuth,
                // 携带商品 [可选]
                bid: item.bid,
                cover: item.cover,
                name: item.name,
                despcription: item.description,
                price: item.price,
                origin_price: item.price,
            }
        })
    }

    render() {
        let n=0
        this.props.carList.forEach(item=>{
            if(item.ischeck){
                n++
            }
        })
        let {uid,nickname,stuAuth,head_url,
            cover,legend_1,legend_2,legend_3,
            name,ISBN,publisher,grade,author,signature,description,
            price,origin_price,getSelf,address,isFavo} = this.state.item;
        
        let commentItems = this.state.commentList.map(comment=>{
            return (
                <div key={comment.cid} className={style["search-item"]}>
                    <div className={style["item-list"]}>
                        <Image className={style["imgs"]} fallback={imgFallback}
                            src={'/apis'+comment.head_url} width={30} height={30}/>
                        <div className={style["search-text"]}>
                            <p className={style["search-name"]}>{comment.nickname}</p>
                            <div className={style["search-msg"]}>
                                {comment.comment}
                            </div>
                            <p className={style["search-time"]}>
                                {new Date(comment.buildtime).toLocaleString()}
                            </p>
                        </div>
                    </div>
                </div>
            )
        }) 

        return (
            <div className={style.msg}>
                {header({title:`${this.state.item.name}`, history:this.props.history})}

                 { this.state.loading 
                    ? <SkeletonDIY></SkeletonDIY>
                    : <>
                        <div className={style.user}>
                            <Image className={style["img"]} src={'/apis'+head_url} width={50} height={50} 
                                 fallback={require("../../common/imageDefault/imgloaderr.png").default}/>
                            <div className={style.name}>
                                <h3>{nickname}</h3>
                                <p>签名：{signature}</p>
                            </div>
                            { stuAuth ?
                                <div className={style.student}>
                                    <span className={style.cert}>{certificate_icon}</span>
                                    <span className={style.ren}>学生认证</span>
                                </div> : null
                            }
                        </div>
                        <div className={style.address}>
                            <div className={style.price}>
                                <div className={style.all}>
                                    <span className={style.fu}>￥</span>
                                    <span className={style.newPrice}>{price}</span>
                                    <span className={style.oldPrice}>原价￥{origin_price}</span>
                                </div>
                                <span className={style.yun}>运费</span>
                                <span className={style.store}>{getSelf?"支持自提":""}</span>
                            </div>
                            <div className={style.msgAdd}>
                                <img src={addressIcon} />
                                <p>发货地址：{address}</p>
                            </div>
                        </div>
                        <div className={style.center} ref={scrollEle => this.scrollEle = scrollEle}>
                            <div className={style.content}>
                                {this.props.match.params.bid
                                    ? <CarouselDIY itemlist = {["/apis/"+cover,"/apis/"+legend_1,"/apis/"+legend_2,"/apis/"+legend_3]} />
                                    : <CarouselDIY itemlist={this.state.imgList} />
                                }
                        
                                <div className={style.title}>基本信息</div>
                                <ul className={style.jiben}>
                                    <li><span>书名</span><p>{name}</p> </li>
                                    <li><span>作者</span> <p>{author}</p></li>
                                    <li><span>出版社</span><p>{publisher}</p></li>
                                    <li><span>ISBN</span><p>{ISBN}</p></li>
                                    <li><span>品相</span><p>{grade}成新</p></li>
                                </ul>

                                <div className={style.title}>商品详情</div>
                                <p className={style.description}>
                                    {(description || description == "undefined") ? "卖家很懒，啥都没说！" : description}
                                </p>
                            </div>
                            <div className={style.footer}>
                                <h3 className={style["footerbox-title"]}>
                                    全部留言 · (<span>{this.state.commentList.length}</span>) 
                                </h3>
                                
                                <div className={style["search-list"]}>
                                    { commentItems }
                                </div>
                            </div>
                        </div>
                        <div className={style.shopp}>
                            {this.state.userinfo.uid != uid
                                ?<><ul className={style.nav}>
                                    <li
                                        onClick={this.setFavorite.bind(this)}
                                    >
                                        <img src={isFavo?favoIcon2:favoIcon} /><p>收藏</p>
                                    </li>

                                    <li
                                        onClick={this.showDrawer.bind(this,true)}
                                    >
                                        <img src={commIcon} /><p>留言</p>
                                    </li>

                                    <li onClick={this.goPrivateChat.bind(this)}>
                                        <img src={chatIcon} /><p>聊一聊</p>
                                    </li>
                                    <li
                                        onClick={()=>this.props.history.push("/shopcart")}
                                    >
                                        <img src={buyIcon} /><p>购物车</p>
                                        {
                                            this.props.carList.length>0?<span className={style["shopp-num"]}>{n}</span>:null
                                        }
                                    
                                    </li>
                                </ul>
                                <button className={style.want} onClick={this.buy}>加入购物车</button>
                                </>
                                :<><ul className={style.nav}>
                                <li
                                    onClick={this.setFavorite.bind(this)}
                                >
                                    <img src={isFavo?favoIcon2:favoIcon} /><p>收藏</p>
                                </li>

                                <li
                                    onClick={this.showDrawer.bind(this,true)}
                                >
                                    <img src={commIcon} /><p>留言</p>
                                </li>

                                <li
                                    onClick={()=>this.props.history.push("/shopcart")}
                                >
                                    <img src={buyIcon} /><p>购物车</p>
                                    {
                                        this.props.carList.length>0?<span className={style["shopp-num"]}>{n}</span>:null
                                    }
                                
                                </li>
                            </ul>
                            <p className={style.want2}>我的在售</p>
                            </>

                            }
                            
                            
                        </div>
                    </>
                 }
                { this.state.flag
                    ? <div  ref={c=>this.mark=c} 
                            className={this.state.flag1?style["buy-mark"]+" "+style.active:style["buy-mark"]}>
                        <div onClick={this.buyBack} 
                            className={this.state.flag1?`${style["buy-max"]} ${style.active}`: style["buy-max"]}></div>

                        <div ref={c=>this.min=c} 
                                className={this.state.flag1?style["buy-min"]+" "+style.active:style["buy-min"]}>
                            <span className={style["min-back"]} onClick={this.buyBack}>X</span>
                            
                            <div className={style["min-msg"]}>
                                <img src={"/apis/"+cover}></img>
                                <div className={style["min-item"]}>
                                <h3 className={style["min-name"]}>{name}</h3>
                                    <p className={style["min-description"]}>{description}</p>
                                    <div className={style["min-price"]}>
                                        <span className={style["min-new"]}>￥{price}</span>
                                        <span className={style["min-old"]}>￥{origin_price}</span>
                                    </div>
                                    <div className={style["min-num"]}>
                                        <span className={style["min-dist"]} onClick={this.dist}>-</span>
                                        <span className={style["min-n"]}> {this.state.num} </span>
                                        <span className={style["min.add"]}  onClick={this.add}>+</span>
                                    </div>
                                    <div className={style["min-btn"]} onClick={this.jiaBuy.bind(this)}> 加入购物车</div>
                                </div>
                            </div>
                        </div>
                    </div> : null
                 }

                 {this.state.visible &&
                    <MAlert callAlert = {this.showDrawer.bind(this)} direction="bottom"
                        closeBtnText = " "
                        closeBtnStyle = {{borderRadius:"0",right:"0",top:"0",backgroundColor:"rgba(0,0,0,0)", width:"100%",height:"calc(100% - 200px)",}}
                    >
                        <div className={style["drawer-body"]}>
                            <p className={style["drawer-title"]}>发送留言</p>
                            <textarea className={style["textarea"]} 
                            placeholder="说点什么吧... ..."
                            rows={3}
                            value = {this.state.currComment}
                            onChange={e=>{
                                this.setState({currComment:e.target.value.substr(0,45)});
                            }}
                            ></textarea>
                            <p className={style["comment-op"]}>
                                <span>{`${this.state.currComment.length}/45`}</span>
                                <button
                                    onClick={this.sendComment.bind(this)}
                                >发送</button>
                            </p>
                        </div>
                    </MAlert>
                 }
            </div>
        )
    }
}
const mapStateToProps = (state)=>{
    return {carList:state.carList};
}
const mapDispatchToProps= (dispatch)=>{
    return {
        getCar:user=>{
            dispatch({type:"CAR",data:user})
        }
    }
}
export default connect(mapStateToProps,mapDispatchToProps)(BookInfoDetails)
